package com.kingwang.demo.springsecuritytokendemo.utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 认证Token工具类
 */
public class AuthenticationTokenUtils {
    private static final String TOKEN_AES_KEY = "CQFT1e3ywZQT1HLYUJBuZ85x6nGZ62KIYyKP0m2P/Ic=";
    private static final String TOKEN_AES_IV = "hhAuzL2bRKuuXriRHU02KQ==";

    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

    private static Cipher ENCRYPTER;

    static {
        Base64.Decoder base64Decoder = Base64.getDecoder();

        byte[] aesKey = base64Decoder.decode(TOKEN_AES_KEY);
        byte[] aesIv = base64Decoder.decode(TOKEN_AES_IV);

        SecretKeySpec keySpec = new SecretKeySpec(aesKey, KEY_ALGORITHM);
        IvParameterSpec ivSpec = new IvParameterSpec(aesIv);

        try {
            ENCRYPTER = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            ENCRYPTER.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        } catch (Exception e) {
            ENCRYPTER = null;
        }
    }

    private AuthenticationTokenUtils() {
        throw new IllegalStateException("Utility class");
    }

    public static String generateToken(String value) throws BadPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException {
        byte[] source = MessageDigest.getInstance("MD5").digest(value.getBytes(StandardCharsets.UTF_8));

        byte[] encrypted = ENCRYPTER.doFinal(source);

        return Base64.getEncoder().encodeToString(encrypted);
    }

//    public static void main(String[] args) throws BadPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException {
////        SecureRandom secureRandom = new SecureRandom();
////
////        byte[] key = new byte[32];
////        secureRandom.nextBytes(key);
////
////        byte[] iv = new byte[16];
////        secureRandom.nextBytes(iv);
////
////        Base64.Encoder base64Encoder = Base64.getEncoder();
////
////        System.out.println("Key: " + base64Encoder.encodeToString(key));
////        System.out.println("IV: " + base64Encoder.encodeToString(iv));
//
//        String s = generateToken("123456");
//        System.out.println(s);
//    }
}
